package de.wolvan.autoupdate;

import java.io.*;
import java.net.*;
import java.security.CodeSource;

public class UpdateFile {
	
	public static boolean delFile(String s) {
		
		System.out.println("Deleting file " + s);
		
		File f = new File(s);

	    // Make sure the file or directory exists and isn't write protected
	    if (!f.exists())
	      throw new IllegalArgumentException(
	          "Delete: no such file or directory: " + s);

	    if (!f.canWrite())
	      throw new IllegalArgumentException("Delete: write protected: "
	          + s);

	    // If it is a directory, make sure it is empty
	    if (f.isDirectory()) {
	      String[] files = f.list();
	      if (files.length > 0)
	        throw new IllegalArgumentException(
	            "Delete: directory not empty: " + s);
	    }

	    // Attempt to delete it
	    boolean success = f.delete();

	    if (!success) {
	      throw new IllegalArgumentException("Delete: deletion failed");
	    } else {
	    	return true;
	    }
	  }
		
	public static void downloadFile(String filename, String urlString) throws MalformedURLException, IOException
    {
    	BufferedInputStream in = null;
    	FileOutputStream fout = null;
    	try
    	{
    		in = new BufferedInputStream(new URL(urlString).openStream());
    		fout = new FileOutputStream(filename);

    		byte data[] = new byte[1024];
    		int count;
    		while ((count = in.read(data, 0, 1024)) != -1)
    		{
    			fout.write(data, 0, count);
    		}
    	}
    	finally
    	{
    		if (in != null)
    			in.close();
    		if (fout != null)
    			fout.close();
    	}
    }
}
